package com.mall.im.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class HttpUtils {

    public static final String RESPONSE_STRING = "responseString";
	public static final String RESPONSE_CODE = "response_code";
	
    public static Map<String, Object> doRequest(String urlString, String jsonString, Map<String, String> propertyMap, String methodType) {
        try { 
            //创建连接 
            URL url = new URL(urlString); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
            connection.setDoOutput(true); 
            connection.setDoInput(true); 
            connection.setRequestMethod(methodType); 
            connection.setUseCaches(false); 
            connection.setInstanceFollowRedirects(true); 
            if(!hashMap.isEmpty()){
            	Set<Entry<String, String>> entrySet = hashMap.entrySet();
            	Iterator<Entry<String, String>> iterator = entrySet.iterator() ;
            	while(iterator.hasNext()){
            		Entry<String, String> next = iterator.next();
            		connection.setRequestProperty(next.getValue(),next.getKey()); 
            	}
            }
            connection.connect(); 

            //POST请求 
            DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 
            out.writeBytes(jsonString);
            out.flush(); 
            out.close(); 

            //读取响应 
            int respCode = connection.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
            System.out.println();
            
            String lines; 
            StringBuffer sb = new StringBuffer(); 
            while ((lines = reader.readLine()) != null) { 
                lines = new String(lines.getBytes(), "utf-8"); 
                sb.append(lines); 
            } 
            reader.close(); 
            connection.disconnect();
            
            Map<String, Object> map = new HashMap<String, Object>();
            map.put(RESPONSE_STRING, sb.toString());
            map.put(RESPONSE_CODE, respCode);
            return map;
            
        } catch (MalformedURLException e) { 
            e.printStackTrace(); 
        } catch (UnsupportedEncodingException e) { 
            e.printStackTrace(); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }
		return null;
    }
    
}
